import dto.AddressDTO;
import dto.UserDTO;

import java.util.Optional;

/**
 * @ClassName: OptionalTest
 * @Description: 判空
 * @Author: zyy
 * @Date: 2020/05/11 15:01
 * @Version: 1.0
 */
public class OptionalTest {
    public static void main(String[] args) {
        UserDTO userDTO = new UserDTO();
        AddressDTO addressDTO = new AddressDTO();
        addressDTO.setCity("深圳");
        userDTO.setAddress(addressDTO);

//        String city = getCity(userDTO);
        String city = getNewCity(userDTO);
        System.out.println(city);
    }

    private static String getCity(UserDTO userDTO) {
        if (userDTO != null) {
            AddressDTO addressDTO = userDTO.getAddress();
            if (addressDTO != null) {
                return addressDTO.getCity();
            }
        }
        return null;
    }

    private static String getCity2(UserDTO userDTO) {
        if (userDTO == null) {
            return null;
        }
        AddressDTO addressDTO = userDTO.getAddress();
        if (addressDTO == null) {
            return null;
        }
        return addressDTO.getCity();
    }

    private static String getNewCity(UserDTO userDTO) {
        return Optional.ofNullable(userDTO)
                .map(user -> user.getAddress())
                .map(address -> address.getCity())
                .orElse(null);
    }
}
